/*
 * @Description:
 * @Autor: HuiSir<273250950@qq.com>
 * @Date: 2023-06-28 10:05:23
 * @LastEditTime: 2023-06-28 11:06:42
 */
export default (Vue) => {
	Vue.directive("dragresize", {
		// 当被绑定的元素插入到 DOM 中时..
		// 可传入min和max最小和最大宽度限制拖拽范围。当前限制最小宽度为原始宽度
		// vue2
		// inserted: function (boxEl) {
		// vue3
		mounted: function(boxEl, {
			value
		}) {
			if (value && (value.min == void 0 || value.max == void 0)) {
				throw new Error("指令`v-dragresize`的参数须为含min及max字段的对象！");
			}

			if (
				value &&
				(typeof value.min !== "number" || typeof value.max !== "number")
			) {
				throw new Error(
					"指令`v-dragresize`的参数min及max须为数字类型（像素值）！"
				);
			}

			const defaultBoxWidth = boxEl.clientWidth; // 容器默认宽度
			const parentWidth = boxEl.parentElement.clientWidth; // 父元素宽度

			let {
				min,
				max
			} = value || {
				min: defaultBoxWidth,
				max: parseInt(parentWidth * 0.9 + ""),
			};

			// 当前容器右侧添加拖拽块
			const dragEl = document.createElement("div");
			dragEl.innerHTML = "┆";
			dragEl.setAttribute(
				"style",
				`
				position: absolute;
				height: 50px;
				width: 10px;
				top: calc(50% - 50px);
				right: -5px;
				background:#d6d6d6;
				line-height:50px;
				text-align:center;
				color: #fff;
				border-radius: 10px;
				cursor: col-resize;
				user-select: none;
				font-size:14px;
			`
			);
			dragEl.onmouseover = (ev) => {
				ev.target.style.background = "#909399";
			};
			dragEl.onmouseout = (ev) => {
				ev.target.style.background = "#d6d6d6";
			};

			boxEl.style.position = "relative";
			boxEl.appendChild(dragEl);

			//鼠标按下
			dragEl.onpointerdown = (ev) => {
				ev.target.style.background = "#909399";
				const startX = ev.clientX; //按下坐标
				const currentBoxWidth = boxEl.clientWidth; //当前容器宽度

				// 全局推拽
				document.onmousemove = (docEv) => {
					const moveLenth = docEv.clientX - startX; // 移动的距离
					let currentWidth = currentBoxWidth + moveLenth;
					//超出限制宽度，无法拖拽
					currentWidth =
						currentWidth < min ? min : currentWidth > max ? max : currentWidth;
					// 设置当前容器宽度
					boxEl.style.width = currentWidth + "px";
					// 设置右侧容器宽度
					boxEl.nextElementSibling.style.width = `calc(100% - ${currentWidth}px)`;
				};

				// 鼠标离开
				document.onmouseup = () => {
					dragEl.style.background = "#d6d6d6";
					document.onmousemove = null;
					document.onmouseup = null;
					dragEl.releasePointerCapture(ev.pointerId); // 取消鼠标捕获
				};

				// 设置鼠标捕获dragEl
				dragEl.setPointerCapture(ev.pointerId);
			};
		},
	});
};
